<template>
	<view class="review-qa-container">
		<!-- 评价与问答标签页 -->
		<view class="tab-container">
			<view class="tab-item" :class="{ active: activeTab === 'reviews' }" @click="switchTab('reviews')">
				评价 ({{ reviews.length }})
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'qa' }" @click="switchTab('qa')">
				问答 ({{ questions.length }})
			</view>
		</view>

		<!-- 评价模块 -->
		<view v-if="activeTab === 'reviews'" class="content-container">
			<!-- 评价列表 -->
			<view class="review-list">
				<view class="review-item" v-for="(review, index) in reviews" :key="index">
					<!-- 用户信息 -->
					<view class="review-header">
						<view class="user-info">
							<!-- 显示登录用户的用户名（复用你的缓存逻辑） -->
							<view class="user-name">{{ review.isCurrentUser ? loginUser.nickname || loginUser.name || loginUser.userName || '当前用户' : review.user.name }}</view>
							<view class="review-date">{{ review.date }}</view>
						</view>
					</view>

					<!-- 评分 -->
					<view class="review-rating">
						<view class="stars">
							<text v-for="i in 5" :key="i" :class="{ filled: i <= review.rating }"
								@click="setRating(i)">★</text>
						</view>
						<text class="rating-text">
							{{ review.rating }} 分
						</text>
					</view>

					<!-- 评价内容 -->
					<view class="review-content">{{ review.content }}</view>

					<!-- 互动按钮 -->
					<view class="review-actions">
						<button class="action-btn" @click="toggleFavorite(review.id)">
							{{ review.isFavorited ? '已点赞' : '点赞' }}
						</button>
						<button class="action-btn" @click="showReplyForm(review.id)">
							回复
						</button>
					</view>

					<!-- 回复表单 -->
					<transition-group name="reply-form-fade" class="reply-form" tag="view"
						v-if="showingReplyForm[review.id]">
						<view key="reply-form" class="reply-form-inner">
							<textarea v-model="replyText[review.id]" placeholder="写下你的回复..." class="reply-textarea"
								@keydown.enter.prevent="submitReply(review.id)"></textarea>
							<view class="form-actions">
								<button class="btn-primary" @click="submitReply(review.id)">
									提交回复
								</button>
								<button class="btn-secondary" @click="hideReplyForm(review.id)">
									取消
								</button>
							</view>
						</view>
					</transition-group>

					<!-- 回复列表 -->
					<view class="replies" v-if="review.replies && review.replies.length > 0">
						<view class="reply-item" v-for="(reply, replyIndex) in review.replies" :key="replyIndex">
							<view class="reply-header">
								<!-- 回复的用户名也显示登录用户（如果是当前用户回复） -->
								<view class="reply-user">{{ reply.isCurrentUser ? loginUser.nickname || loginUser.name || loginUser.userName || '当前用户' : reply.user.name }}:</view>
								<view class="reply-date">{{ reply.date }}</view>
							</view>
							<view class="reply-content">{{ reply.content }}</view>
						</view>
					</view>
				</view>

				<!-- 没有评价时的提示 -->
				<view class="no-data" v-if="reviews.length === 0">
					<view>暂无评价，快来分享你的体验吧！</view>
				</view>
			</view>

			<!-- 发布评价按钮（点击唤起弹窗） -->
			<button class="btn-primary publish-review" @click="openReviewModal">
				发布评价
			</button>
		</view>

		<!-- 问答模块 -->
		<view v-if="activeTab === 'qa'" class="content-container">
			<!-- 提问表单 -->
			<view class="ask-question">
				<view class="ask-title">有关于美食的问题？来提问吧！</view>
				<textarea v-model="questionText" placeholder="请输入你的问题...（例如：这道菜辣吗？分量够两个人吃吗？）" class="question-textarea"
					@keydown.enter.prevent="submitQuestion"></textarea>
				<button class="btn-primary" @click="submitQuestion">
					提交问题
				</button>
			</view>

			<!-- 问题列表 -->
			<view class="question-list">
				<view class="question-item" v-for="(question, index) in questions" :key="index">
					<view class="question-header">
						<!-- 问题的用户名显示登录用户（如果是当前用户提问） -->
						<view class="question-user">{{ question.isCurrentUser ? loginUser.nickname || loginUser.name || loginUser.userName || '当前用户' : question.user.name }}</view>
						<view class="question-date">{{ question.date }}</view>
					</view>
					<view class="question-content">{{ question.question }}</view>

					<!-- 回答状态 -->
					<view class="answer-status" :class="{ answered: question.answers && question.answers.length > 0 }">
						<text v-if="question.answers && question.answers.length > 0">
							已有 {{ question.answers.length }} 个回答
						</text>
						<text v-else>等待回答</text>
					</view>

					<!-- 回答列表 -->
					<view class="answers" v-if="question.answers && question.answers.length > 0">
						<view class="answer-item" v-for="(answer, answerIndex) in question.answers" :key="answerIndex">
							<view class="answer-header">
								<!-- 回答的用户名显示登录用户（如果是当前用户回答） -->
								<view class="answer-user">{{ answer.isCurrentUser ? loginUser.nickname || loginUser.name || loginUser.userName || '当前用户' : answer.user.name }}</view>
								<view class="answer-date">{{ answer.date }}</view>
								<view class="answer-tag" v-if="answer.isMerchantAnswer">商家回答</view>
							</view>
							<view class="answer-content">{{ answer.answer }}</view>
						</view>
					</view>

					<!-- 回答按钮 -->
					<button class="btn-secondary answer-btn" @click="toggleAnswerForm(question.id)"
						:disabled="!question.answers || question.answers.length === 0 && !showingAnswerForm[question.id]">
						{{
              question.answers && question.answers.length > 0
                ? showingAnswerForm[question.id]
                  ? '收起回答回复'
                  : '用户回复'
                : '我来回答'
            }}
					</button>
					<!-- 回答表单 -->
					<transition-group name="answer-form-fade" class="answer-form" tag="view"
						v-if="showingAnswerForm[question.id]">
						<view key="answer-form" class="answer-form-inner">
							<textarea v-model="answerText[question.id]" placeholder="写下你的回答..." class="answer-textarea"
								@keydown.enter.prevent="submitAnswer(question.id)"></textarea>
							<view class="form-actions">
								<button class="btn-primary" @click="submitAnswer(question.id)">
									提交回答
								</button>
								<button class="btn-secondary" @click="hideAnswerForm(question.id)">
									取消
								</button>
							</view>
						</view>
					</transition-group>
				</view>
			</view>
		</view>

		<!-- 发布评价弹窗（自定义弹窗，覆盖在页面上层） -->
		<view v-if="showReviewModal" class="review-modal" @click.self="closeReviewModal">
			<view class="modal-content" @click.stop>
				<view class="modal-title">发布评价</view>

				<!-- 评分选择 -->
				<view class="modal-rating">
					<view class="stars">
						<text v-for="i in 5" :key="i" :class="{ filled: i <= reviewForm.rating }"
							@click="reviewForm.rating = i">★</text>
					</view>
					<text class="rating-text">
						{{ reviewForm.rating }} 分
					</text>
				</view>

				<textarea v-model="reviewForm.content" placeholder="分享你的用餐体验..." class="modal-textarea"></textarea>

				<view class="modal-actions">
					<button class="btn-primary" @click="submitReview" :disabled="!reviewForm.content.trim()">
						提交评价
					</button>
					<button class="btn-secondary" @click="closeReviewModal">
						取消
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		reactive,
		toRefs,
		onMounted,
		onUnmounted
	} from 'vue';
	import {
		reviewData
	} from '@/api/review.js';
	// 引入你提供的缓存工具函数（与用户页一致）
	import {
		getStorageToken,
		getStorageUser
	} from "@/utils/storage.js";

	export default {
		setup() {
			// 初始化响应式数据
			const state = reactive({
				activeTab: reviewData.data.activeTab,
				reviews: reviewData.data.reviews.map(review => ({
					...review,
					isFavorited: false,
					// 标记是否是当前登录用户的评价
					isCurrentUser: review.user.id === (getStorageUser()?.id || '')
				})),
				questions: reviewData.data.questions.map(question => ({
					...question,
					// 标记是否是当前登录用户的问题
					isCurrentUser: question.user.id === (getStorageUser()?.id || ''),
					answers: question.answers?.map(answer => ({
						...answer,
						// 标记是否是当前登录用户的回答
						isCurrentUser: answer.user.id === (getStorageUser()?.id || '')
					}))
				})),
				showingReplyForm: {},
				showingAnswerForm: {},
				replyText: {},
				answerText: {},
				questionText: '',
				showReviewModal: false,
				reviewForm: {
					content: '',
					rating: 5 // 默认评分
				},
				// 存储当前登录用户信息（与你的用户页逻辑一致）
				loginUser: getStorageUser() || {},
				isLogin: !!getStorageToken()
			});

			// 解构响应式数据
			const {
				activeTab,
				reviews,
				questions,
				showingReplyForm,
				showingAnswerForm,
				replyText,
				answerText,
				questionText,
				showReviewModal,
				reviewForm,
				loginUser,
				isLogin
			} = toRefs(state);

			// 标签页切换方法
			const switchTab = (tabName) => {
				state.activeTab = tabName;
			};

			// 切换点赞状态功能
			const toggleFavorite = (reviewId) => {
				const review = state.reviews.find((r) => r.id === reviewId);
				if (review) {
					review.isFavorited = !review.isFavorited;
					const statusText = review.isFavorited ? '点赞成功' : '已取消点赞';
					uni.showToast({
						title: statusText,
						icon: 'none'
					});
				}
			};

			// 评价功能 - 显示回复表单
			const showReplyForm = (reviewId) => {
				state.showingReplyForm[reviewId] = true;
				state.replyText[reviewId] = '';
			};

			// 评价功能 - 隐藏回复表单
			const hideReplyForm = (reviewId) => {
				state.showingReplyForm[reviewId] = false;
				state.replyText[reviewId] = '';
			};

			// 评价功能 - 提交回复
			const submitReply = (reviewId) => {
				const replyContent = state.replyText[reviewId];
				if (!replyContent.trim()) return;

				const review = state.reviews.find((r) => r.id === reviewId);
				if (review) {
					review.replies = review.replies || [];
					// 提交的回复使用当前登录用户信息
					review.replies.push({
						user: {
							id: state.loginUser.id || '',
							name: state.loginUser.nickname || state.loginUser.name || state.loginUser.userName || '当前用户'
						},
						date: new Date().toLocaleDateString(),
						content: replyContent,
						isCurrentUser: true // 标记为当前用户的回复
					});
					hideReplyForm(reviewId);
					uni.showToast({
						title: '回复成功',
						icon: 'success'
					});
				}
			};

			// 评分设置
			const setRating = (i) => {
				// 若需修改已有评价评分，可扩展逻辑
			};

			// 打开发布评价弹窗
			const openReviewModal = () => {
				// 未登录拦截（与你的用户页逻辑一致）
				if (!state.isLogin) {
					uni.showToast({
						title: "请先登录",
						icon: "none"
					});
					uni.navigateTo({
						url: "/pages/user/login"
					});
					return;
				}
				state.showReviewModal = true;
				// 重置表单
				state.reviewForm.content = '';
				state.reviewForm.rating = 5;
			};

			// 关闭发布评价弹窗
			const closeReviewModal = () => {
				state.showReviewModal = false;
			};

			// 提交评价（弹窗内操作）
			const submitReview = () => {
				if (!reviewForm.value.content.trim()) return;

				state.reviews.unshift({
					id: state.reviews.length + 1,
					// 发布的评价使用当前登录用户信息
					user: {
						id: state.loginUser.id || '',
						name: state.loginUser.nickname || state.loginUser.name || state.loginUser.userName || '当前用户'
					},
					date: new Date().toLocaleDateString(),
					content: reviewForm.value.content,
					rating: reviewForm.value.rating,
					isFavorited: false,
					replies: [],
					isCurrentUser: true // 标记为当前用户的评价
				});

				// 关闭弹窗并提示
				closeReviewModal();
				uni.showToast({
					title: '评价发布成功',
					icon: 'success'
				});
			};

			// 问答功能 - 提交问题
			const submitQuestion = () => {
				// 未登录拦截
				if (!state.isLogin) {
					uni.showToast({
						title: "请先登录",
						icon: "none"
					});
					uni.navigateTo({
						url: "/pages/user/login"
					});
					return;
				}

				const questionContent = state.questionText.trim();
				if (!questionContent) return;

				state.questions.unshift({
					id: state.questions.length + 1,
					// 提交的问题使用当前登录用户信息
					user: {
						id: state.loginUser.id || '',
						name: state.loginUser.nickname || state.loginUser.name || state.loginUser.userName || '当前用户'
					},
					date: new Date().toLocaleDateString(),
					question: questionContent,
					answers: [],
					isCurrentUser: true // 标记为当前用户的问题
				});
				state.questionText = '';
				uni.showToast({
					title: '问题提交成功',
					icon: 'success'
				});
			};

			// 问答功能 - 切换回答表单
			const toggleAnswerForm = (questionId) => {
				// 未登录拦截
				if (!state.isLogin) {
					uni.showToast({
						title: "请先登录",
						icon: "none"
					});
					uni.navigateTo({
						url: "/pages/user/login"
					});
					return;
				}

				state.showingAnswerForm[questionId] = !state.showingAnswerForm[questionId];
				if (state.showingAnswerForm[questionId]) {
					state.answerText[questionId] = '';
				}
			};

			// 问答功能 - 隐藏回答表单
			const hideAnswerForm = (questionId) => {
				state.showingAnswerForm[questionId] = false;
				state.answerText[questionId] = '';
			};

			// 问答功能 - 提交回答
			const submitAnswer = (questionId) => {
				const answerContent = state.answerText[questionId].trim();
				if (!answerContent) return;

				const question = state.questions.find((q) => q.id === questionId);
				if (question) {
					question.answers = question.answers || [];
					// 提交的回答使用当前登录用户信息
					question.answers.push({
						user: {
							id: state.loginUser.id || '',
							name: state.loginUser.nickname || state.loginUser.name || state.loginUser.userName || '当前用户'
						},
						date: new Date().toLocaleDateString(),
						answer: answerContent,
						isMerchantAnswer: false,
						isCurrentUser: true // 标记为当前用户的回答
					});
					hideAnswerForm(questionId);
					uni.showToast({
						title: '回答提交成功',
						icon: 'success'
					});
				}
			};

			// 监听用户信息更新（与你的用户页逻辑一致）
			const handleUserInfoUpdate = (newUserInfo) => {
				state.loginUser = newUserInfo;
				// 同步更新已有评价/问题/回答的用户名
				state.reviews = state.reviews.map(review => ({
					...review,
					isCurrentUser: review.user.id === newUserInfo.id,
					user: review.isCurrentUser ? {
						...review.user,
						name: newUserInfo.nickname || newUserInfo.name || newUserInfo.userName || '当前用户'
					} : review.user
				}));
				state.questions = state.questions.map(question => ({
					...question,
					isCurrentUser: question.user.id === newUserInfo.id,
					user: question.isCurrentUser ? {
						...question.user,
						name: newUserInfo.nickname || newUserInfo.name || newUserInfo.userName || '当前用户'
					} : question.user,
					answers: question.answers?.map(answer => ({
						...answer,
						isCurrentUser: answer.user.id === newUserInfo.id,
						user: answer.isCurrentUser ? {
							...answer.user,
							name: newUserInfo.nickname || newUserInfo.name || newUserInfo.userName || '当前用户'
						} : answer.user
					}))
				}));
			};

			onMounted(() => {
				// 监听用户信息更新事件（与你的用户页一致）
				uni.$on("userInfoUpdated", handleUserInfoUpdate);
			});

			onUnmounted(() => {
				// 清理监听
				uni.$off("userInfoUpdated", handleUserInfoUpdate);
			});

			return {
				activeTab,
				reviews,
				questions,
				showingReplyForm,
				showingAnswerForm,
				replyText,
				answerText,
				questionText,
				showReviewModal,
				reviewForm,
				loginUser,
				isLogin,
				switchTab,
				toggleFavorite,
				showReplyForm,
				hideReplyForm,
				submitReply,
				setRating,
				openReviewModal,
				closeReviewModal,
				submitReview,
				submitQuestion,
				toggleAnswerForm,
				hideAnswerForm,
				submitAnswer
			};
		}
	};
</script>

<style scoped>
	/* 容器基础样式 */
	.review-qa-container {
		max-width: 800px;
		margin: 0 auto;
		padding: 20rpx;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
			'Helvetica Neue', sans-serif;
		color: #333;
	}

	/* 标签栏 */
	.tab-container {
		display: flex;
		border-bottom: 1px solid #eee;
		margin-bottom: 20rpx;
	}

	.tab-item {
		padding: 10rpx 20rpx;
		cursor: pointer;
		margin-right: 10rpx;
		border-bottom: 4rpx solid transparent;
		transition: all 0.3s ease;
		font-size: 28rpx;
	}

	.tab-item.active {
		border-bottom-color: #007bff;
		color: #007bff;
		font-weight: 500;
	}

	/* 内容容器 */
	.content-container {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 16rpx;
		box-shadow: 0 0 16rpx rgba(0, 0, 0, 0.05);
	}

	/* 评价/问答列表通用 */
	.review-list,
	.question-list {
		margin-top: 15rpx;
	}

	.review-item,
	.question-item {
		border-bottom: 1px solid #eee;
		padding-bottom: 20rpx;
		margin-bottom: 20rpx;
	}

	/* 头部信息（用户+日期） */
	.review-header,
	.question-header,
	.reply-header,
	.answer-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.user-name,
	.question-user,
	.reply-user,
	.answer-user {
		font-weight: 500;
		font-size: 28rpx;
	}

	.review-date,
	.question-date,
	.reply-date,
	.answer-date {
		font-size: 24rpx;
		color: #999;
	}

	/* 评分区域 */
	.review-rating {
		margin: 8rpx 0;
		display: flex;
		align-items: center;
	}

	.stars {
		display: flex;
		margin-right: 10rpx;
	}

	.stars text {
		color: #ffc107;
		cursor: pointer;
		transition: color 0.2s;
		font-size: 28rpx;
	}

	.stars text.filled {
		color: #ff9800;
	}

	.rating-text {
		font-size: 26rpx;
		color: #666;
	}

	/* 内容文本 */
	.review-content,
	.question-content,
	.reply-content,
	.answer-content {
		line-height: 1.6;
		margin-bottom: 15rpx;
		font-size: 26rpx;
	}

	/* 操作按钮（点赞/回复） */
	.review-actions {
		display: flex;
		gap: 10rpx;
		margin-bottom: 10rpx;
	}

	.action-btn {
		background: none;
		border: none;
		color: #007bff;
		cursor: pointer;
		padding: 6rpx 10rpx;
		border-radius: 8rpx;
		transition: background-color 0.3s ease;
		font-size: 26rpx;
	}

	.action-btn:hover {
		background-color: #f0f8ff;
	}

	/* 点赞激活态 */
	.action-btn.favorited {
		color: #ff9800;
	}

	/* 回复/回答区域 */
	.replies,
	.answers {
		margin-top: 10rpx;
		padding-left: 15rpx;
		border-left: 4rpx solid #eee;
	}

	.reply-item,
	.answer-item {
		margin-bottom: 15rpx;
		padding-bottom: 10rpx;
		border-bottom: 1px solid #f5f5f5;
	}

	/* 所有输入框样式 */
	.reply-textarea,
	.question-textarea,
	.answer-textarea,
	.modal-textarea {
		width: 100%;
		min-height: 80rpx;
		padding: 12rpx;
		border: 1px solid #ddd;
		border-radius: 8rpx;
		resize: vertical;
		margin-bottom: 12rpx;
		font-family: inherit;
		font-size: 24rpx;
		box-sizing: border-box;
		background-color: #fff;
	}

	/* 表单操作按钮 */
	.form-actions {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
	}

	.btn-primary {
		background-color: #007bff;
		color: #fff;
		border: none;
		padding: 14rpx 28rpx;
		border-radius: 8rpx;
		cursor: pointer;
		transition: background-color 0.3s ease;
		font-size: 24rpx;
	}

	.btn-primary:hover {
		background-color: #0056b3;
	}

	.btn-secondary {
		background-color: #f1f1f1;
		color: #333;
		border: 1px solid #ddd;
		padding: 14rpx 28rpx;
		border-radius: 8rpx;
		cursor: pointer;
		transition: all 0.3s ease;
		font-size: 24rpx;
	}

	.btn-secondary:hover {
		background-color: #e5e5e5;
	}

	/* 无数据提示 */
	.no-data {
		text-align: center;
		padding: 40rpx;
		color: #999;
		font-style: italic;
		font-size: 26rpx;
	}

	/* 发布评价弹窗样式（核心新增） */
	.review-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.modal-content {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		width: 85%;
		max-width: 500rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
	}

	.modal-title {
		font-size: 30rpx;
		font-weight: 600;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.modal-rating {
		margin: 20rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.modal-actions {
		display: flex;
		justify-content: space-between;
		gap: 10rpx;
		margin-top: 20rpx;
	}

	/* Uniapp小程序适配 */
	button::after {
		border: none;
	}

	textarea {
		padding: 12rpx !important;
	}

	/* 问答模块补充样式 */
	.ask-question {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 12rpx;
	}

	.ask-title {
		font-size: 26rpx;
		font-weight: 500;
		margin-bottom: 12rpx;
		color: #333;
	}

	.btn-submit-question {
		width: 100%;
		background-color: #007bff;
		color: #fff;
		border: none;
		padding: 18rpx 0;
		border-radius: 8rpx;
		font-size: 26rpx;
		font-weight: 500;
	}

	.answer-status {
		font-size: 24rpx;
		color: #28a745;
		margin-bottom: 15rpx;
	}

	.answer-tag {
		background-color: #007bff;
		color: #fff;
		font-size: 22rpx;
		padding: 4rpx 12rpx;
		border-radius: 6rpx;
		margin-left: 10rpx;
	}

	.btn-user-reply {
		width: 100%;
		background-color: #f1f1f1;
		color: #333;
		border: 1px solid #ddd;
		padding: 14rpx 0;
		border-radius: 8rpx;
		font-size: 24rpx;
		margin-top: 10rpx;
	}
</style>